/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: 下午8.5.c
> Author:
> Mail: 
> Created Time: Mon 05 Aug 2024 03:30:49 AM PDT
***************************************************/



//通过消息队列进程a给b发送5个学员，b收到后显示。b给a回送收到消息，a收到后结束。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>


typedef struct student
{
	int code;
	char name[10];
	int age;
}STU;

struct msgbuf{
	long mtype;     //消息类型，必须>0
	char mtext[50]; //消息文本
};
int main(int argc,const char* argv[])
{
	key_t key = 0;
	int msgid = 0;
	int ret = 0;
	key = ftok("./",1); //查找编号
	if(key == -1)
	{
		perror("ftok");
		exit(-1);
	}

	msgid = msgget(key,IPC_CREAT|0666); //创建队列
	if(msgid == -1)
	{
		perror("msgget");
		exit(-1);
	}
	struct msgbuf data;
	memset(&data,0,sizeof(struct msgbuf));
	while(1)
	{
		ret = msgrcv(msgid,&data,sizeof(struct msgbuf)-sizeof(long),1,0); //出队
		if(ret ==-1)
		{
			perror("msgcv");
			exit(-1);
		}
		STU num;
		memcpy(&num,data.mtext,sizeof(STU));
		printf("student is %d\n %s\n %d\n",num.code,num.name,num.age);
	}
	printf("ok");
	struct msgbuf msg;
	memset(&msg,0,sizeof(struct msgbuf));
	msg.mtype = 2;
	strcpy(msg.mtext,"传输完成");

	
	ret = msgsnd(msgid,&msg,sizeof(struct msgbuf)-sizeof(long),0);   //入队
if(ret == -1)
{
	perror("msgsnd");
	exit(-1);
}



ret = msgctl(msgid,IPC_RMID,NULL);   //释放队列
if(ret == -1)
{
	perror("msgctl");
	exit(-1);
}
return 0;
}
